package cn.tlb.xutilsdownload;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Environment;
import android.test.AndroidTestCase;
import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import cn.tlb.utils.BitmapUtil;
import cn.tlb.upload.Form;
import cn.tlb.upload.FormUtil;
import cn.tlb.upload.Input;

/**
 * Created by 汤林冰 on 2016/1/5 17:48.
 */
public class TestCase extends AndroidTestCase {
    private static final String TAG = TestCase.class.getSimpleName();
    private static final String PIC_DIR = Environment.getExternalStorageDirectory() + "/Pictures/Screenshots";
    private static final String FILENAME = PIC_DIR +"/" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".png";
    private static final String FILENAME_JPG = PIC_DIR +"/" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".jpg";
    private static final String LOCAL_HOST = "http://192.168.47.146:8080/http/servlet/FileUploadServlet";

    String path = PIC_DIR + "/sample1.png";
    int maxHeight = 720;
    int maxWidth = 1080;
    int maxSizeInKB = 100/*KB*/;

    public void testCompress2() throws Exception {
        String compressedPath = BitmapUtil.getCompressedPath(path, maxWidth, maxHeight, maxSizeInKB);
        uploadFile(new File(compressedPath));
    }

    public void testMultyCompress() throws Exception {
        String compressedPath = BitmapUtil.getCompressedPath(PIC_DIR + "/5.png", maxWidth, maxHeight, maxSizeInKB);
        uploadFile(new File(compressedPath));
    }

    public void testCompressBitmap() throws Exception {
        Bitmap bitmap = BitmapFactory.decodeFile(PIC_DIR + "/2.png");
        String compressedPath = BitmapUtil.getCompressedPath(bitmap, maxWidth, maxHeight, maxSizeInKB);
        uploadFile(new File(compressedPath));
    }

    public void testLocalCompress() throws FileNotFoundException, InterruptedException {
        File file;
        Bitmap bitmap;

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        int originWidth = options.outWidth;
        int originHeight = options.outHeight;
        long length = new File(path).length();

        //step 1: 小于给定尺寸, 压缩质量
        if(originWidth < maxWidth && originHeight < maxHeight){
            if(length/1024 <= maxSizeInKB) {
                file = new File(path);
            }else {
                bitmap = BitmapFactory.decodeFile(path);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int quality = 100;
                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
                Log.i(TAG, String.format("size=%sBytes", baos.size()));
                boolean isCompressed = false;
                while (quality > 0 && baos.size() / 1024 > maxSizeInKB) {
                    quality -= 5;
                    baos.reset();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
                    Log.i(TAG, String.format("quality=%s,size=%sBytes", quality, baos.size()));
                    isCompressed = true;
                }
                if (isCompressed) {
                    bitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(baos.toByteArray()));
                }
                file = new File(FILENAME_JPG);
                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, new FileOutputStream(file));
            }
        }else {

            // 3.1: 按尺寸调整 inSampleSize 压缩
            options.inSampleSize = Math.min(options.outWidth / maxWidth, options.outHeight / maxHeight);
            options.inJustDecodeBounds = false;
            // 压缩后 options.outWidth >= maxWidth, options.outHeight >= maxHeight, 需要进一步压缩
            bitmap = BitmapFactory.decodeFile(path, options);
            file = new File(FILENAME_JPG);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file));
            //uploadFile(file);
            Thread.sleep(1000);


            Bitmap source = BitmapFactory.decodeFile(file.getAbsolutePath());
            Matrix matrix = new Matrix();
            float sx = Math.min((float) maxWidth / source.getWidth(), (float) maxHeight / source.getHeight());
            matrix.postScale(sx, sx);
            source = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, false);
            file = new File(FILENAME_JPG);
            source.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file));
            //uploadFile(file);
            Thread.sleep(1000);


            bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int quality = 100;
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            Log.i(TAG, String.format("size=%sBytes", baos.size()));
            boolean isCompressed = false;
            while (quality > 0 && baos.size() / 1024 > maxSizeInKB) {
                quality -= 5;
                baos.reset();
                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
                Log.i(TAG, String.format("quality=%s,size=%sBytes", quality, baos.size()));
                isCompressed = true;
            }
            if (isCompressed) {
                bitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(baos.toByteArray()));
            }
            file = new File(FILENAME_JPG);
            //jpeg格式正常压缩
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, new FileOutputStream(file));
        }
        uploadFile(file);
    }

    public void testQuality() throws FileNotFoundException {
        Bitmap bitmap = BitmapFactory.decodeFile(PIC_DIR + "/20160107_142216.jpg");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
        Log.i(TAG, String.format("size=%sBytes", baos.size()));
        boolean isCompressed = false;
        while (quality > 0 && baos.size() / 1024 > maxSizeInKB) {
            quality -= 5;
            baos.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            Log.i(TAG, String.format("quality=%s,size=%sBytes", quality, baos.size()));
            isCompressed = true;
        }
        if (isCompressed) {
            bitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(baos.toByteArray()));
        }

        File file = new File(FILENAME_JPG);
        //jpeg格式正常压缩
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, new FileOutputStream(file));

        uploadFile(file);
    }


    public void testMatrixDimen() throws FileNotFoundException {
        Bitmap source = BitmapFactory.decodeFile(PIC_DIR + "/20160107_144311.jpg");

        Matrix matrix = new Matrix();
        float sx = Math.min((float) maxHeight / source.getWidth(), (float) maxWidth / source.getHeight());
        matrix.postScale(sx, sx);
        source = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, false);

        File file = new File(FILENAME_JPG);
        source.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file));

        uploadFile(file);
    }

    public void testSample() throws FileNotFoundException {
        String path = PIC_DIR + "/2.png";
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        int originWidth = options.outWidth;
        int originHeight = options.outHeight;
        // 3.1: 按尺寸调整 inSampleSize 压缩
        options.inSampleSize = Math.min(originHeight / maxHeight, originWidth / maxWidth);
        options.inJustDecodeBounds = false;
        // 压缩后 options.outWidth >= maxWidth, options.outHeight >= maxHeight, 需要进一步压缩
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
        File file = new File(FILENAME_JPG);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file));
        uploadFile(file);
    }

    public void testCleanPath() throws IOException {
        boolean b = BitmapUtil.cleanTempDir();
        Log.i(TAG, "cleanTempDir -->  "+b);
    }


    public void testOut() throws FileNotFoundException {
        File[] list = new File(PIC_DIR).listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String filename) {
                return filename.endsWith(".png") || filename.endsWith(".jpg");
            }
        });

        Log.i(TAG, Arrays.toString(list));

        Form form = new Form(LOCAL_HOST, "POST");
        for(File file : list){
            form.inputs.add(Input.newFileInput(file.getName(), file.getAbsolutePath()));
        }
        new FormUtil().uploadMultipartForm(form, new MyListener());
    }

    public static void uploadFile(File file){
        Form form = new Form(LOCAL_HOST, "POST");
        form.inputs.add(Input.newFileInput(file.getName(), file.getAbsolutePath()));
        new FormUtil().uploadMultipartForm(form, new MyListener());
    }

    public void testService(){
        Form form = new Form("http://192.168.50.211:5151/service/user/resource/create/version/1.5", "POST");

        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("type", "1");
        map.put("title", "upload_test");
        map.put("cateId", "1");
        map.put("description", "map description. description description description...");

        for(Map.Entry<String, String> entry : map.entrySet()){
            form.inputs.add(Input.newTextInput(entry.getKey(), entry.getValue()));
        }

        File file = new File(PIC_DIR+File.pathSeparator+"map_ex.zip");
        form.inputs.add(Input.newFileInput("zip", file.getAbsolutePath()));


        new FormUtil().uploadMultipartForm(form, new MyListener());
    }

    private static class MyListener implements FormUtil.OnSubmitListener{

        @Override
        public void onStart() {

        }

        @Override
        public void onError(Throwable th) {
            Log.i(TAG, "onError--->"+th);
        }

        @Override
        public void onUploading(String absFilePath, long totalSize, long uploadSize, int progress) {

        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onSuccess(String result) {
            Log.i(TAG, "onSuccess--->"+result);
        }

        @Override
        public void onFailed(int responseCode) {

        }

        @Override
        public void onFinish() {

        }
    }
}
